package com.aliqin.mytel;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mobile.auth.gatewayauth.AuthRegisterViewConfig;
import com.mobile.auth.gatewayauth.AuthRegisterXmlConfig;
import com.mobile.auth.gatewayauth.AuthUIConfig;
import com.mobile.auth.gatewayauth.AuthUIControlClickListener;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.PreLoginResultListener;
import com.mobile.auth.gatewayauth.TokenResultListener;
import com.mobile.auth.gatewayauth.model.TokenRet;
import com.mobile.auth.gatewayauth.ui.AbstractPnsViewDelegate;

public class MainLandscapeActivity extends Activity {
    private static final int SERVICE_TYPE_AUTH = 1;//号码认证
    private static final int SERVICE_TYPE_LOGIN = 2;//一键登录
    private PhoneNumberAuthHelper mAlicomAuthHelper;
    private TokenResultListener mTokenListener;
    private Button mVaildBtn, mLoginBtn, mLoginDlgBtn, mPreLoginBtn;
    private TextView mRetTV;
    private ProgressDialog mProgressDialog;
    private String token;
    private int mScreenWidthDp;
    private int mScreenHeightDp;
    private int mOldScreenOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
    private boolean checkRet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mVaildBtn = findViewById(R.id.vaild_button);
        mRetTV = findViewById(R.id.operator_name_tv);
        mLoginBtn = findViewById(R.id.login_button);
        mLoginDlgBtn = findViewById(R.id.login_dlg_button);
        mPreLoginBtn = findViewById(R.id.prelogin_button);
        init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mOldScreenOrientation != getRequestedOrientation()) {
            setRequestedOrientation(mOldScreenOrientation);
        }
    }

    private void updateScreenSize(int authPageScreenOrientation) {
        int screenHeightDp = AppUtils.px2dp(getApplicationContext(), AppUtils.getPhoneHeightPixels(MainLandscapeActivity.this));
        int screenWidthDp = AppUtils.px2dp(getApplicationContext(), AppUtils.getPhoneWidthPixels(MainLandscapeActivity.this));
        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        if (authPageScreenOrientation == ActivityInfo.SCREEN_ORIENTATION_BEHIND) {
            authPageScreenOrientation = getRequestedOrientation();
        }
        if (authPageScreenOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                || authPageScreenOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
                || authPageScreenOrientation == ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE) {
            rotation = Surface.ROTATION_90;
        }
        switch (rotation) {
        case Surface.ROTATION_90:
            mScreenWidthDp = screenWidthDp;
            mScreenHeightDp = screenHeightDp;
            break;
        }
    }

    private void init() {
        /*
         *   1.init get token callback Listener
         */
        mTokenListener = new TokenResultListener() {
            @Override
            public void onTokenSuccess(final String ret) {
                MainLandscapeActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Log.e("xxxxxx", "onTokenSuccess:" + ret);

                        /*
                         *   setText just show the result for get token。
                         *   use ret to verfiy number。
                         */
                        hideLoadingDialog();
                        TokenRet tokenRet = null;
                        try {
                            tokenRet = JSON.parseObject(ret, TokenRet.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        if (tokenRet != null && ("600024").equals(tokenRet.getCode())) {
                            mRetTV.setText("终端自检成功:\n" + ret);
                        }

                        if (tokenRet != null && ("600001").equals(tokenRet.getCode())) {
                            mRetTV.setText("唤起授权页成功:\n" + ret);
                        }

                        if (tokenRet != null && ("600000").equals(tokenRet.getCode())) {
                            token = tokenRet.getToken();
                            mAlicomAuthHelper.quitLoginPage();
                            mRetTV.setText("获取token成功:\n" + ret);
                        }
                    }
                });
            }

            @Override
            public void onTokenFailed(final String ret) {
                Log.e("xxxxxx", "onTokenFailed:" + ret);
                MainLandscapeActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        /*
                         *  setText just show the result for get token
                         *  do something when getToken failed, such as use sms verify code.
                         */
                        hideLoadingDialog();
                        mAlicomAuthHelper.hideLoginLoading();
                        mRetTV.setText("失败:\n" + ret);
//                        mAlicomAuthHelper.quitLoginPage();
                    }
                });
            }
        };

        /*
         *   2.init AlicomAuthHelper with tokenListener
         */
        mAlicomAuthHelper = PhoneNumberAuthHelper.getInstance(this, mTokenListener);
        mAlicomAuthHelper.setAuthListener(mTokenListener);
        /*
         *   3.set debugMode when app is in debug mode, sdk will print log in debug mode
         */
        mAlicomAuthHelper.setLoggerEnable(true);
        mAlicomAuthHelper.setAuthSDKInfo("7KHffk2Cn1j17+QVA2zbJfdDteDSUDspB/s+FUoAhyXmQ/wueAQBcpMDOVLrp5lt5BDIGxDrCuTBZk7TcR4CxAQvHnJUPIaCI5dscbBFqHgHVI8Yoy0nYwsFo8Gyd2RZ6MbUAZr3lsnPQsA+UW1MZY9EP94x0TrXmwEJkU5xJgmOJfCSekYWHP5xNc0as/aWkTmNrjFyb5//93cAMwQllH0FFEFF+GEd7XMvm6ap/g4BD8676+z29MbePXPjoY6u3VrNTMkksQHW1EolxJkw+y1FhIxpm9II");
        /*
         *   使用一键登录传入 SERVICE_TYPE_LOGIN
         *   使用号码校验传入 SERVICE_TYPE_AUTH
         */
        mAlicomAuthHelper.checkEnvAvailable(SERVICE_TYPE_LOGIN);

        mVaildBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLoadingDialog("正在获取认证token");
                mAlicomAuthHelper.getVerifyToken(5000);
            }
        });

        mLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                configLoginTokenLand();
                showLoadingDialog("正在请求登录Token");
                mAlicomAuthHelper.getLoginToken(MainLandscapeActivity.this, 5000);
            }
        });


        mLoginDlgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                configLoginTokenLandDialog();
                showLoadingDialog("正在请求登录Token");
                mAlicomAuthHelper.getLoginToken(MainLandscapeActivity.this, 5000);
            }
        });

        /**
         * 控件点击事件回调
         */
        mAlicomAuthHelper.setUIClickListener(new AuthUIControlClickListener() {
            @Override
            public void onClick(String code, Context context, JSONObject jsonObj) {
                Log.e("authSDK", "OnUIControlClick:code=" + code + ", jsonObj=" + (jsonObj == null ? "" : jsonObj.toJSONString()));
            }
        });

        mPreLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAlicomAuthHelper.accelerateLoginPage(5000, new PreLoginResultListener() {
                    @Override
                    public void onTokenSuccess(final String vendor) {
                        MainLandscapeActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mRetTV.setText(vendor + "预取号成功！");
                            }
                        });
                    }

                    @Override
                    public void onTokenFailed(final String vendor, final String ret) {
                        MainLandscapeActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mRetTV.setText(vendor + "预取号失败:\n" + ret);
                            }
                        });
                    }
                });
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void showLoadingDialog(String hint) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        }
        mProgressDialog.setMessage(hint);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
    }

    public void hideLoadingDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }


    private ImageView createLandDialogPhoneNumberIcon(int leftMargin) {
        ImageView imageView = new ImageView(this);
        int size = AppUtils.dp2px(this, 23);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(size, size);
        layoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
        layoutParams.leftMargin = leftMargin;
        imageView.setLayoutParams(layoutParams);
        imageView.setBackgroundResource(R.drawable.phone);
        imageView.setScaleType(ImageView.ScaleType.CENTER);
        return imageView;
    }

    private View createLandDialogCustomSwitchView() {
        View v = LayoutInflater.from(this).inflate(R.layout.custom_switch_other, new RelativeLayout(this), false);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
        v.setLayoutParams(layoutParams);
        return v;
    }

    private void configLoginTokenLand() {
        mAlicomAuthHelper.removeAuthRegisterXmlConfig();
        mAlicomAuthHelper.removeAuthRegisterViewConfig();
        mAlicomAuthHelper.addAuthRegisterXmlConfig(new AuthRegisterXmlConfig.Builder()
        .setLayout(R.layout.custom_port_dialog_action_bar, new AbstractPnsViewDelegate() {
            @Override
            public void onViewCreated(View view) {
                findViewById(R.id.tv_title).setVisibility(View.GONE);
                findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mAlicomAuthHelper.quitLoginPage();
                    }
                });
            }
        })
        .build());
        int authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
        if (Build.VERSION.SDK_INT == 26) {
            mOldScreenOrientation = getRequestedOrientation();
            setRequestedOrientation(authPageOrientation);
            authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_BEHIND;
        }
        mAlicomAuthHelper.setAuthUIConfig(new AuthUIConfig.Builder()
                                          .setAppPrivacyOne("《自定义隐私协议》", "https://www.baidu.com")
                                          .setAppPrivacyColor(Color.GRAY, Color.RED)
                                          .setPrivacyState(false)
                                          .setSwitchAccHidden(true)
                                          .setSloganHidden(true)
                                          .setNavHidden(true)
                                          .setStatusBarHidden(true)
                                          .setCheckboxHidden(false)
                                          .setLogoOffsetY(55)
                                          .setLogoImgPath("phone")
                                          .setLogoWidth(50)
                                          .setLogoHeight(50)
                                          .setNumFieldOffsetY(120)
                                          .setLogBtnOffsetY(166)
                                          .setLogBtnMarginLeftAndRight((mScreenHeightDp - 339) / 2)
                                          .setPrivacyMargin(115)
                                          .setLogBtnWidth(339)
                                          .setAuthPageActIn("in_activity", "out_activity")
                                          .setAuthPageActOut("in_activity", "out_activity")
                                          .setVendorPrivacyPrefix("《")
                                          .setVendorPrivacySuffix("》")
                                          .setPageBackgroundPath("page_background_color")
                                          .setScreenOrientation(authPageOrientation)
                                          .create());
    }

    private void configLoginTokenLandDialog() {
        mAlicomAuthHelper.removeAuthRegisterXmlConfig();
        mAlicomAuthHelper.removeAuthRegisterViewConfig();
        int authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
        if (Build.VERSION.SDK_INT == 26) {
            mOldScreenOrientation = getRequestedOrientation();
            setRequestedOrientation(authPageOrientation);
            authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_BEHIND;
        }
        updateScreenSize(authPageOrientation);
        final int dialogWidth = (int) (mScreenWidthDp * 0.63);
        final int dialogHeight = (int) (mScreenHeightDp * 0.6);
        final int logBtnOffsetY = dialogHeight / 2 - 50;
        final View switchContainer = createLandDialogCustomSwitchView();
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) switchContainer.findViewById(R.id.container_other).getLayoutParams();
        layoutParams.width = AppUtils.dp2px(MainLandscapeActivity.this, dialogWidth / 2 - 60);
        mAlicomAuthHelper.addAuthRegistViewConfig("image_icon",
                new AuthRegisterViewConfig.Builder()
                .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_NUMBER)
                .setView(createLandDialogPhoneNumberIcon(AppUtils.dp2px(getApplicationContext(), 30)))
                .build());
        mAlicomAuthHelper.addAuthRegistViewConfig("switch_other", new AuthRegisterViewConfig.Builder()
                .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_NUMBER)
                .setView(switchContainer).build());
        mAlicomAuthHelper.addAuthRegisterXmlConfig(new AuthRegisterXmlConfig.Builder()
        .setLayout(R.layout.custom_land_dialog, new AbstractPnsViewDelegate() {
            @Override
            public void onViewCreated(View view) {
                findViewById(R.id.tv_title).setVisibility(View.GONE);
                findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mAlicomAuthHelper.quitLoginPage();
                    }
                });
                int iconTopMargin = AppUtils.dp2px(getContext(), logBtnOffsetY + 50);
                View iconContainer = findViewById(R.id.container_icon);
                RelativeLayout.LayoutParams iconLayout = (RelativeLayout.LayoutParams) iconContainer.getLayoutParams();
                iconLayout.topMargin = iconTopMargin;
                iconLayout.width = AppUtils.dp2px(getContext(), dialogWidth / 2 - 60);
            }
        })
        .build());
        mAlicomAuthHelper.setAuthUIConfig(new AuthUIConfig.Builder()
                                          .setAppPrivacyOne("《自定义隐私协议》", "https://www.baidu.com")
                                          .setAppPrivacyColor(Color.GRAY, Color.RED)
                                          .setNavHidden(true)
                                          .setCheckboxHidden(true)
                                          .setLogoHidden(true)
                                          .setSloganHidden(true)
                                          .setSwitchAccHidden(true)
                                          .setNumberFieldOffsetX(60)
                                          .setNumberLayoutGravity(Gravity.LEFT)
                                          .setNumberSize(24)
                                          .setNumFieldOffsetY(logBtnOffsetY - 35)
                                          .setPrivacyOffsetY_B(20)
                                          .setPageBackgroundPath("dialog_page_background")
                                          .setLogBtnOffsetY(logBtnOffsetY)
                                          .setLogBtnOffsetX(30)
                                          .setLogBtnMarginLeftAndRight(0)
                                          .setLogBtnWidth(174)
                                          .setLogBtnLayoutGravity(Gravity.LEFT)
                                          .setLogBtnHeight(51)
                                          .setDialogWidth(dialogWidth)
                                          .setDialogHeight(dialogHeight)
                                          .setDialogBottom(false)
                                          .setAuthPageActIn("in_activity", "out_activity")
                                          .setAuthPageActOut("in_activity", "out_activity")
                                          .setVendorPrivacyPrefix("《")
                                          .setVendorPrivacySuffix("》")
                                          .setProtocolGravity(Gravity.CENTER_VERTICAL)
                                          .setScreenOrientation(authPageOrientation)
                                          .create());
    }

}

